//
//  Signature.m
//  Opper
//
//  Created by Le Dung on 4/19/13.
//  Copyright (c) 2013 LeDung. All rights reserved.
//

#import "Signature.h"

@interface Signature ()

@end

@implementation Signature

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)viewDidAppear:(BOOL)animated
{
    [StyleClass barButtonItemEdit:self left:YES right:NO];
}
-(void)leftPress
{
    [self.navigationController popViewControllerAnimated:YES];
    
}


- (IBAction)uploadImage:(id)sender
{
    
    	NSData *imageData = UIImageJPEGRepresentation(self.mainImage.image, 90);

    NSString *returnString;
    
	NSString *urlString =@"http://localhost/lsever/indexLS.php";
	NSURL *url = [NSURL URLWithString:urlString];
	NSString *filename = @"userfile";
	NSMutableURLRequest *request= [[NSMutableURLRequest alloc] initWithURL:url] ;
    
	[request setURL:[NSURL URLWithString:urlString]];
	[request setHTTPMethod:@"POST"];
	NSString *boundary = @"---------------------------14737809831466499882746641449";
	NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
	[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
    
	NSMutableData *postbody = [NSMutableData data];
	//NSMutableDictionary * params = [[NSMutableDictionary alloc] initWithObjects:[[NSArray alloc] initWithObjects:@"great problem", @"infront of my house",nil] forKeys:[[NSArray alloc] initWithObjects:@"problem",@"location",nil]];
    //here Webservices is my class name
	if(imageData != nil)
	{
		[postbody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
		[postbody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filetype=\"image/jpeg\"; filename=\"%@.jpg\"\r\n", filename] dataUsingEncoding:NSUTF8StringEncoding]];
		[postbody appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
		[postbody appendData:[NSData dataWithData:imageData]];
	}
    
	[postbody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
	[request setHTTPBody:postbody];
    
	NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
	returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
	[request release];
    
    
    
    
    
    
//    /*
//	 turning the image into a NSData object
//	 getting the image back out of the UIImageView
//	 setting the quality to 90
//     */
//	NSData *imageData = UIImageJPEGRepresentation(self.mainImage.image, 90);
//
//    NSString *urlString = @"http://localhost/lsever/indexLS.php";
//	
//	// setting up the request object now
//	NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
//	[request setURL:[NSURL URLWithString:urlString]];
//	[request setHTTPMethod:@"POST"];
//	
//	/*
//	 add some header info now
//	 we always need a boundary when we post a file
//	 also we need to set the content type
//	 
//	 You might want to generate a random boundary.. this is just the same
//	 as my output from wireshark on a valid html post
//     */
//	NSString *boundary = @"---------------------------14737809831466499882746641449";
//	NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
//	[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
//	
//	/*
//	 now lets create the body of the post
//     */
//	NSMutableData *body = [NSMutableData data];
//	[body appendData:[[NSString stringWithFormat:@"rn--%@rn",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
//	[body appendData:[@"Content-Disposition: form-data; name=\"ledung\"; filename=\"ipodfile.jpg\"rn" dataUsingEncoding:NSUTF8StringEncoding]];
//	[body appendData:[@"Content-Type: application/octet-streamrnrn" dataUsingEncoding:NSUTF8StringEncoding]];
//	[body appendData:[NSData dataWithData:imageData]];
//	[body appendData:[[NSString stringWithFormat:@"rn--%@--rn",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
//	// setting the body of the post to the reqeust
//	[request setHTTPBody:body];
//	
//    
//    NSLog(@"body----------- : %@",body);
//	// now lets make the connection to the web
//	NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
//    NSLog(@"data :%@",returnData);
//	NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
//    
//    NSLog(@"hhjg %@",returnString);
	}

-(void)acceptPress
{
    
    UIAlertView *alertView =[[UIAlertView alloc]initWithTitle:@"Use this signature" message:nil delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:@"don't use !", nil];
    alertView.delegate =self;
    [alertView show ];
    [alertView release];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex) {
        case 0:
            [self save];
            
            
            break;
            
        default:
            break;
    }
}
-(void)cancelPress
{
    [self reset];
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    [StyleClass createNavi:self andTitle:@"Ondertekenen"];
    [self.cancelButton addTarget:self action:@selector(cancelPress) forControlEvents:UIControlEventTouchUpInside];
    
    [self buttonTarget];
    red = 0.0/255.0;
    green= 0.0/255.0;
    blue= 0.0/255.0;
    brush=1;
    opacity=1.0;
}


-(void)buttonTarget
{
    [self.acceptButton addTarget:self action:@selector(acceptPress) forControlEvents:UIControlEventTouchUpInside];
    [self.acceptButton setBackgroundImage:[StyleClass nGreen] forState:UIControlStateNormal];
    
    
    [self.cancelButton addTarget:self action:@selector(cancelPress) forControlEvents:UIControlEventTouchUpInside];
    [self.cancelButton setBackgroundImage:[StyleClass nRed] forState:UIControlStateNormal];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    
    mouseSwipe=NO;
    UITouch *touch = [touches anyObject];
    lastPoint = [touch locationInView:self.view];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
    mouseSwipe=YES;
    UITouch *touch = [touches anyObject];
    CGPoint currentPoint = [touch locationInView:self.view];
    
    
    UIGraphicsBeginImageContext(self.view.frame.size);
    [self.tempDrawImage.image drawInRect:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
    CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y);
    CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
    CGContextSetLineWidth(UIGraphicsGetCurrentContext(), brush);
    CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), red, green, blue, opacity);
    CGContextSetBlendMode(UIGraphicsGetCurrentContext(), kCGBlendModeNormal);
    CGContextStrokePath(UIGraphicsGetCurrentContext());
    self.tempDrawImage.image=UIGraphicsGetImageFromCurrentImageContext();
    [self.tempDrawImage setAlpha:opacity];
    UIGraphicsEndImageContext();
    
    lastPoint=currentPoint;
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    if (!mouseSwipe) {
        UIGraphicsBeginImageContext(self.view.frame.size);
        [self.tempDrawImage.image drawInRect:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
        CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
        CGContextSetLineWidth(UIGraphicsGetCurrentContext(), brush);
        CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), red, green, blue, 1.0);
        CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
        CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
        CGContextStrokePath(UIGraphicsGetCurrentContext());
        CGContextFlush(UIGraphicsGetCurrentContext());
        self.tempDrawImage.image=UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }
    UIGraphicsBeginImageContext(self.mainImage.frame.size);
    [self.mainImage.image drawInRect:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)blendMode:kCGBlendModeNormal alpha:1.0];
    [self.tempDrawImage.image drawInRect:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)blendMode:kCGBlendModeNormal alpha:1.0];
    self.mainImage.image=UIGraphicsGetImageFromCurrentImageContext();
    self.tempDrawImage.image=nil;
    UIGraphicsEndImageContext();
}

-(void)cancelPencil:(UIButton*)sender{
    [sender setFrame:CGRectMake(sender.frame.origin.x, sender.frame.origin.y+10, sender.frame.size.width, sender.frame.size.height)];
    
}


-(IBAction)reset{
    self.mainImage.image=nil;
}
-(IBAction)save{
    
    UIGraphicsBeginImageContextWithOptions(self.mainImage.bounds.size, NO, 0.0);
    [self.mainImage.image drawInRect:CGRectMake(0, 0, self.mainImage.frame.size.width, self.mainImage.frame.size.height)];
    UIImage *saveImg = UIGraphicsGetImageFromCurrentImageContext();
    [GetData App].signImage=saveImg;
    UIGraphicsEndImageContext();
    UIImageWriteToSavedPhotosAlbum(saveImg, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}



- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
	UIAlertView *alert;
	
	// Unable to save the image
	if (error)
		alert = [[UIAlertView alloc] initWithTitle:@"Save Image"
										   message:@"UnSuccessful"
										  delegate:nil cancelButtonTitle:@"OK"
								 otherButtonTitles:nil];
	else
    {
		alert = [[UIAlertView alloc] initWithTitle:nil
										   message:@"Successful"
										  delegate:nil cancelButtonTitle:@"OK"
								 otherButtonTitles:nil];
    
        Payment *page=[[[Payment alloc]init]autorelease];
        [StyleClass currentScreen:self andDestination:page andHideBackButton:YES];

    }
	[alert show];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)dealloc {
    [_acceptButton release];
    [_cancelButton release];
    [super dealloc];
}
@end
